package org.androidnotebook;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class BookDbAdapter {
	public static final String KEY_ID = "_id";
	public static final String KEY_TITLE = "title";
	public static final String KEY_WEIGHT = "weight";

	private static final String TAG = "BookDbAdapter";
	private DatabaseHelper mDbHelper;
	private SQLiteDatabase mDb;

	/**
	 * Database creation sql statement
	 */
	private static final String BOOK_TABLE_CREATE = "create table book (_id integer primary key autoincrement, "
			+ "title text not null, weight integer not null);";
	private static final String PAGE_TABLE_CREATE = "create table page (_id integer primary key autoincrement, "
		+ "bookid integer not null, title text not null, weight integer not null, body text);";


	private static final String DATABASE_NAME = "notebook";
	private static final String DATABASE_TABLE = "book";
	private static final int DATABASE_VERSION = 2;
	private static final int WEIGHT_GAP=100;

	private final Context mCtx;

	private static class DatabaseHelper extends SQLiteOpenHelper {

		DatabaseHelper(Context context) {
			super(context, DATABASE_NAME, null, DATABASE_VERSION);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			db.execSQL(BOOK_TABLE_CREATE);
			db.execSQL(PAGE_TABLE_CREATE);
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
					+ newVersion + ", which will destroy all old data");
			db.execSQL("DROP TABLE IF EXISTS book");
			onCreate(db);
		}
	}

	/**
	 * Constructor - takes the context to allow the database to be
	 * opened/created
	 * 
	 * @param ctx
	 *            the Context within which to work
	 */
	public BookDbAdapter(Context ctx) {
		this.mCtx = ctx;
	}

	/**
	 * Open the books database. If it cannot be opened, try to create a new
	 * instance of the database. If it cannot be created, throw an exception to
	 * signal the failure
	 * 
	 * @return this (self reference, allowing this to be chained in an
	 *         initialization call)
	 * @throws SQLException
	 *             if the database could be neither opened or created
	 */
	public BookDbAdapter open() throws SQLException {
		mDbHelper = new DatabaseHelper(mCtx);
		mDb = mDbHelper.getWritableDatabase();
		return this;
	}

	public void close() {
		mDbHelper.close();
	}

	/**
	 * Create a new book using the title provided. If the book is successfully
	 * created return the new rowId for that book, otherwise return a -1 to
	 * indicate failure.
	 * 
	 * @param title
	 *            the title of the book
	 * @return rowId or -1 if failed
	 */
	public long createBook(String title) {
		ContentValues initialValues = new ContentValues();
		initialValues.put(KEY_TITLE, title);

		int weight=WEIGHT_GAP;
		Cursor mCursor =
		mDb.query(true, DATABASE_TABLE, new String[] { "max("+KEY_WEIGHT+")" },null, null, null, null, null, null);

		if (mCursor != null && mCursor.moveToFirst()) {
			weight=mCursor.getInt(0)+WEIGHT_GAP;
		}

		initialValues.put(KEY_WEIGHT, weight);

		return mDb.insert(DATABASE_TABLE, null, initialValues);
	}

	/**
	 * Delete the book with the given rowId
	 * 
	 * @param rowId
	 *            id of book to delete
	 * @return true if deleted, false otherwise
	 */
	public boolean deleteBook(long rowId) {
		boolean result;
		
		PageDbAdapter pageDbAdapter=new PageDbAdapter(mCtx);
		pageDbAdapter.open();
		result=pageDbAdapter.deletePagesforBook(rowId);
		result=mDb.delete(DATABASE_TABLE, KEY_ID + "=" + rowId, null) > 0;
		
		return result;
	}

	/**
	 * Return a Cursor over the list of all books in the database
	 * 
	 * @return Cursor over all books
	 */
	public Cursor fetchAllBooks() {

		return mDb.query(DATABASE_TABLE, new String[] {KEY_ID, KEY_TITLE }, null,
				null, null, null, null);
	}

	/**
	 * Return a Cursor positioned at the book that matches the given rowId
	 * 
	 * @param rowId
	 *            id of book to retrieve
	 * @return Cursor positioned to matching book, if found
	 * @throws SQLException
	 *             if book could not be found/retrieved
	 */
	public Cursor fetchBook(long rowId) throws SQLException {

		Cursor mCursor =

		mDb.query(true, DATABASE_TABLE, new String[] { KEY_ID, KEY_TITLE },
				KEY_ID + "=" + rowId, null, null, null, null, null);
		if (mCursor != null) {
			mCursor.moveToFirst();
		}
		return mCursor;

	}

	/**
	 * Update the book using the details provided. The book to be updated is
	 * specified using the rowId, and it is altered to use the title
	 * values passed in
	 * 
	 * @param rowId
	 *            id of book to update
	 * @param title
	 *            value to set book title to
	 * @return true if the book was successfully updated, false otherwise
	 */
	public boolean updateBook(long rowId, String title) {
		ContentValues args = new ContentValues();
		args.put(KEY_TITLE, title);

		return mDb.update(DATABASE_TABLE, args, KEY_ID + "=" + rowId, null) > 0;
	}
}
